import { createRouter, createWebHistory } from 'vue-router'
import { getToken } from '@/utils/storage.js'

const router = createRouter({
    history: createWebHistory(),
    routes: [
        // 首页路由 - 首屏加载的关键页面，不添加延迟加载
        {
            path: '/',
            name: 'Total',
            component: () => import(
                /* webpackChunkName: "home" */
                '@/views/total/total.vue'
            ),
            meta: {
                title: '校园运动会赛事平台',
                requiresAuth: false
            }
        },
        // 登录页面 - 认证相关，需要快速加载
        {
            path: '/login',
            name: 'Login',
            component: () => import(
                /* webpackChunkName: "auth" */
                '@/views/login/Login.vue'
            ),
            meta: {
                title: '用户登录',
                requiresAuth: false
            }
        },
        // 忘记密码页面
        {
            path: '/forgot-password',
            name: 'ForgotPassword',
            component: () => import(
                /* webpackChunkName: "auth" */
                '@/views/login/ForgotPassword.vue'
            ),
            meta: {
                title: '忘记密码',
                requiresAuth: false
            }
        },
        // 注册页面
        {
            path: '/register',
            name: 'Register',
            component: () => import(
                /* webpackChunkName: "auth" */
                '@/views/login/Register.vue'
            ),
            meta: {
                title: '账号注册',
                requiresAuth: false
            }
        },
        // 管理员模块路由 - 按功能分组
        {
            path: '/admin',
            name: 'Admin',
            component: () => import(
                /* webpackChunkName: "admin-home" */
                '@/views/admin/Home.vue'
            ),
            meta: {
                title: '管理员首页',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        {
            path: '/admin/users',
            name: 'UserManagement',
            component: () => import(
                /* webpackChunkName: "admin-user" */
                '@/views/admin/user-management.vue'
            ),
            meta: {
                title: '用户管理',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        {
            path: '/admin/projects',
            name: 'ProjectManagement',
            component: () => import(
                /* webpackChunkName: "admin-project" */
                '@/views/admin/project-management.vue'
            ),
            meta: {
                title: '项目管理',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        {
            path: '/admin/schedule',
            name: 'ScheduleManagement',
            component: () => import(
                /* webpackChunkName: "admin-schedule" */
                '@/views/admin/schedule-management.vue'
            ),
            meta: {
                title: '赛程管理',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        {
            path: '/admin/score-record',
            name: 'ScoreRecord',
            component: () => import(
                /* webpackChunkName: "admin-score" */
                '@/views/admin/score-record.vue'
            ),
            meta: {
                title: '成绩录入',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        {
            path: '/admin/score-display',
            name: 'ScoreDisplay',
            component: () => import(
                /* webpackChunkName: "admin-score" */
                '@/views/admin/ScoreDisplay.vue'
            ),
            meta: {
                title: '成绩公示',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        {
            path: '/admin/enrollment',
            name: 'EnrollmentManagement',
            component: () => import(
                /* webpackChunkName: "admin-enrollment" */
                '@/views/admin/enrollment-management.vue'
            ),
            meta: {
                title: '报名管理',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        // 文件和证书管理模块
        {
            path: '/admin/files',
            name: 'FileManagement',
            component: () => import(
                /* webpackChunkName: "admin-files" */
                '@/views/file/fileManagement.vue'
            ),
            meta: {
                title: '文件管理',
                requiresAuth: true,
                roles: ['管理员', '老师']
            }
        },
        {
            path: '/admin/certificates',
            name: 'CertificateManagement',
            component: () => import(
                /* webpackChunkName: "admin-certificates" */
                '@/views/certificate/certificateManagement.vue'
            ),
            meta: {
                title: '证书管理',
                requiresAuth: true,
                roles: ['管理员', '老师']
            }
        },
        // 系统配置模块
        {
            path: '/admin/backup',
            name: 'BackupManagement',
            component: () => import(
                /* webpackChunkName: "admin-system" */
                '@/views/admin/backgroundBackup.vue'
            ),
            meta: {
                title: '数据备份与恢复',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        {
            path: '/admin/system-config',
            name: 'SystemConfig',
            component: () => import(
                /* webpackChunkName: "admin-system" */
                '@/views/admin/system-config.vue'
            ),
            meta: {
                title: '系统参数配置',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        {
            path: '/admin/dict-type',
            name: 'DictType',
            component: () => import(
                /* webpackChunkName: "admin-dict" */
                '@/views/admin/dict-type.vue'
            ),
            meta: {
                title: '字典类型管理',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        {
            path: '/admin/dict-data',
            name: 'DictData',
            component: () => import(
                /* webpackChunkName: "admin-dict" */
                '@/views/admin/dict-data.vue'
            ),
            meta: {
                title: '字典数据管理',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        // 系统监控模块
        {
            path: '/admin/operation-log',
            name: 'OperationLog',
            component: () => import(
                /* webpackChunkName: "admin-monitor" */
                '@/views/system/operationLog/index.vue'
            ),
            meta: {
                title: '操作日志',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        {
            path: '/admin/operation-log-statistics',
            name: 'OperationLogStatistics',
            component: () => import(
                /* webpackChunkName: "admin-monitor" */
                '@/views/system/operationLog/statistics.vue'
            ),
            meta: {
                title: '日志统计分析',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        {
            path: '/admin/exception-handling',
            name: 'ExceptionHandling',
            component: () => import(
                /* webpackChunkName: "admin-monitor" */
                '@/views/system/exceptionHandling/index.vue'
            ),
            meta: {
                title: '异常处理',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        {
            path: '/admin/exception-statistics',
            name: 'ExceptionStatistics',
            component: () => import(
                /* webpackChunkName: "admin-monitor" */
                '@/views/system/exceptionHandling/statistics.vue'
            ),
            meta: {
                title: '异常统计分析',
                requiresAuth: true,
                roles: ['管理员']
            }
        },
        // 角色首页路由 - 按角色分组
        {
            path: '/teacher',
            name: 'Teacher',
            component: () => import(
                /* webpackChunkName: "teacher" */
                '@/views/teacher/Home.vue'
            ),
            meta: {
                title: '教师首页',
                requiresAuth: true,
                roles: ['管理员', '老师']
            }
        },
        {
            path: '/user',
            name: 'User',
            component: () => import(
                /* webpackChunkName: "student" */
                '@/views/student/Home.vue'
            ),
            meta: {
                title: '学生首页',
                requiresAuth: true
            }
        },
        {
            path: '/referee',
            name: 'Referee',
            component: () => import(
                /* webpackChunkName: "referee" */
                '@/views/referee/Home.vue'
            ),
            meta: {
                title: '裁判首页',
                requiresAuth: true,
                roles: ['管理员', '老师', '裁判']
            }
        },
        // 404错误页面 - 放在最后
        {
            path: '/:pathMatch(.*)*',
            name: 'NotFound',
            component: () => import(
                /* webpackChunkName: "error" */
                '@/views/error/404.vue'
            ),
            meta: {
                title: '页面不存在',
                requiresAuth: false
            }
        }
    ]
})

// 预加载关键路由组件
const preloadRoutes = [
    'Admin', 'UserManagement', 'ProjectManagement', 'Teacher', 'User'
]

// 路由预加载函数
function preloadRoute(routeName) {
    const route = router.resolve({ name: routeName })
    if (route.matched.length > 0) {
        const component = route.matched[0].components?.default
        if (component && typeof component === 'function') {
            component()
        }
    }
}

// 延迟预加载非关键路由
setTimeout(() => {
    preloadRoutes.forEach(routeName => {
        preloadRoute(routeName)
    })
}, 2000) // 2秒后开始预加载

// 全局前置守卫
router.beforeEach((to, from, next) => {
    // 设置页面标题
    document.title = to.meta.title ? `${to.meta.title} - 校园运动会管理系统` : '校园运动会管理系统'

    const token = getToken()

    // 不需要认证的页面直接通过
    if (!to.meta.requiresAuth) {
        next()
        return
    }

    // 需要认证但未登录，重定向到首页
    if (!token) {
        next({
            path: '/',
            query: { redirect: to.fullPath }
        })
        return
    }

    // 这里可以添加角色权限检查
    // 暂时简化处理，后续可以实现基于角色的权限控制
    next()
})

// 全局后置钩子 - 用于预加载可能访问的页面
router.afterEach((to) => {
    // 根据当前路由预加载可能访问的相关页面
    const relatedRoutes = {
        'Admin': ['UserManagement', 'ProjectManagement', 'ScheduleManagement'],
        'User': ['Teacher', 'Referee'],
        'Login': ['Admin', 'User']
    }

    const related = relatedRoutes[to.name]
    if (related && related.length > 0) {
        // 延迟500ms后预加载相关页面，避免影响当前页面加载
        setTimeout(() => {
            related.forEach(routeName => {
                preloadRoute(routeName)
            })
        }, 500)
    }
})

export default router